package com.chat.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.common.entity.DisableGroup;
import com.chat.common.entity.Group;
import com.chat.common.entity.User;
import com.chat.common.vo.R;
import com.chat.login.service.AuthService;
import com.chat.login.service.GroupService;
import com.chat.login.service.IDisableGroupService;
import com.chat.login.service.IUserService;
import com.chat.openfeign.client.BusinessDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    BusinessDataService businessDataService;

    @Autowired
    IDisableGroupService iDisableGroupService;

    @Autowired
    IUserService iUserService;

    @Autowired
    AuthService authService;

    @Override
    public R getGroupByAccount(String groupAccount) {
        R<Group> groupByAccount = businessDataService.getGroupByAccount(groupAccount);
        DisableGroup disableGroup;
        if (groupByAccount.getCode() != 200) {
            return R.failed("找不到" + groupAccount + "群");
        } else if(groupByAccount.getData().getState() == 1){
            return R.failed(groupAccount + "群，未被冻结");
        } else {
            disableGroup = iDisableGroupService.getBaseMapper().selectOne(
                    new LambdaQueryWrapper<DisableGroup>()
                            .eq(DisableGroup::getGroupId, groupByAccount.getData().getId()));
        }
        return R.succeed(disableGroup);
    }

    @Override
    public R getGroupByGroupLeader(String account, String groupAccount) {
        User user = iUserService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getAccount, account)
        );
        if(user == null){
            return R.failed("账号错误");
        } else if(user.getState() != 1){
            return R.failed("当前账号已被冻结，请先申述账号");
        }
        R<Group> groupByAccount = businessDataService.getGroupByAccount(account);
        if (groupByAccount.getCode() != 200) {
            return R.failed("找不到" + account + "群");
        } else if(user.getId().equals(groupByAccount.getData().getGroupLeaderId())){
            return authService.getAccountOfMail(user);
        }
        return R.failed("账号错误");
    }
}
